package android.microblog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.microblog.Abstract.MicroblogFactory;
import android.microblog.Abstract.MicroblogOAuth;
import android.microblog.Common.MicroblogType;
import android.microblog.Common.Util;
import android.microblog.Data.DataHelper;
import android.microblog.Data.UserInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;

public class AuthorizeActivity extends Activity {
	/** Called when the activity is first created. */
	MicroblogOAuth auth = null;
	String CallBackUrl = "microblog://AuthorizeActivity";
	Dialog dialog = null;
	String LOG_TAG="AuthorizeActivity";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.authorize);
		LinearLayout layout = (LinearLayout) findViewById(R.id.auth_layout);
		Util.AutoBackground(this, layout, R.drawable.sinaweibo,
				R.drawable.sinaweibo_h);

		View diaView = View.inflate(this, R.layout.dialog, null);
		dialog = new Dialog(AuthorizeActivity.this, R.style.dialog);
		dialog.setContentView(diaView);
		dialog.show();

		ImageButton stratBtn = (ImageButton) diaView
				.findViewById(R.id.btn_start);
		stratBtn.setOnClickListener(clickHandler);
	}

	private OnClickListener clickHandler = new OnClickListener() {
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_start: // Do something when click button1
				auth = MicroblogFactory.GetInstance(MicroblogType.SINA).getOAuth();
				auth.RequestAccessToken(AuthorizeActivity.this, CallBackUrl);
				break;
			case R.id.btnExit: // Do something when click button2
				break;
			case R.id.btnAdd: // Do something when click button2
				break;
			}
			if (dialog != null)
				dialog.dismiss();
		}
	};

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		UserInfo user = auth.GetAccessToken(intent);
		if (user != null) {
			DataHelper helper = new DataHelper(this);
			String uid = user.getUserId();
			if (helper.HaveUserInfo(uid)) {
				helper.UpdateUserInfo(user);
				Log.e(LOG_TAG, "update user info");
			} else {
				helper.SaveUserInfo(user);
				Log.e(LOG_TAG, "add user info");
			}
		}
	}

}
